import axios from 'axios';
import router from "@/router";
import {useUserStore} from "@/stores/modules/useUserStore";
import {ElMessage} from "element-plus";

const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_URL,
    timeout: 5000
})

const userStore = useUserStore();

service.interceptors.request.use((config) => {
    //前置处理
    if (userStore.token) {
        config.headers['token'] = userStore.token
    }
    return config;
}, (error) => {
    return Promise.reject(error)
})

service.interceptors.response.use((response) => {
    //后置
    const res = response.data
    if (res.code != 200) {
        ElMessage({
            type:"warning",
            message:res.msg
        })
        return Promise.reject(new Error(res.msg));
    }
    return response
}, (error) => {
    let {data} = error.response;
    console.log(data)
    if (data.msg === '请先登录' || data.msg === '身份已过期，请重新登录') {
        userStore.CLEAR_USERINFO();
        userStore.CLEAR_TOKEN();
        router.push({
            path: '/login',
            query: {
                redirect: router.currentRoute.value.fullPath
            }
        })
    }
    return Promise.reject(error)
})
export default service;